const app = getApp()

Page({
  data: {
    orderId: null,
    productId: null,
    storeId: null,
    userId: null,
    rating: 5,
    content: '',
    images: [],
    anonymous: false,
    selectedTags: [],
    tagOptions: ['味道好', '分量足', '服务好', '物超所值', '包装精美', '新鲜', '送餐快'],
    uploadProgress: 0,
    submitting: false,
    maxImageCount: 9,
    maxContentLength: 500,
    product: {}, // 商品信息
    order: {}, // 订单信息
  },

  onLoad(options) {
    const { orderId, productId, storeId } = options
    
    if (!orderId || !productId || !storeId) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    this.setData({
      orderId: parseInt(orderId),
      productId: parseInt(productId),
      storeId: parseInt(storeId),
      userId: app.globalData.userInfo?.id || 0
    })
    
    this.loadProductInfo()
    this.loadOrderInfo()
  },

  // 加载商品信息
  loadProductInfo() {
    wx.showLoading({
      title: '加载中',
    })
    
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/products/${this.data.productId}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            product: res.data.data
          })
        } else {
          wx.showToast({
            title: '获取商品信息失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 加载订单信息
  loadOrderInfo() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/orders/${this.data.orderId}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            order: res.data.data
          })
        }
      }
    })
  },

  // 评分变化
  onRatingChange(e) {
    this.setData({
      rating: e.detail.value
    })
  },

  // 评价内容变化
  onContentInput(e) {
    this.setData({
      content: e.detail.value
    })
  },

  // 切换匿名评价
  toggleAnonymous() {
    this.setData({
      anonymous: !this.data.anonymous
    })
  },

  // 选择标签
  toggleTag(e) {
    const tag = e.currentTarget.dataset.tag
    const selectedTags = [...this.data.selectedTags]
    
    const index = selectedTags.indexOf(tag)
    if (index > -1) {
      selectedTags.splice(index, 1)
    } else {
      selectedTags.push(tag)
    }
    
    this.setData({
      selectedTags
    })
  },

  // 选择图片
  chooseImage() {
    const { images, maxImageCount } = this.data
    const remaining = maxImageCount - images.length
    
    if (remaining <= 0) {
      wx.showToast({
        title: `最多上传${maxImageCount}张图片`,
        icon: 'none'
      })
      return
    }
    
    wx.chooseImage({
      count: remaining,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          images: [...images, ...res.tempFilePaths]
        })
      }
    })
  },

  // 预览图片
  previewImage(e) {
    const { url } = e.currentTarget.dataset
    wx.previewImage({
      current: url,
      urls: this.data.images
    })
  },

  // 删除图片
  deleteImage(e) {
    const { index } = e.currentTarget.dataset
    const images = [...this.data.images]
    images.splice(index, 1)
    this.setData({ images })
  },

  // 上传图片
  uploadImages() {
    return new Promise((resolve, reject) => {
      const { images } = this.data
      
      if (images.length === 0) {
        resolve([])
        return
      }
      
      const uploadedImages = []
      let uploadedCount = 0
      
      images.forEach((filePath, index) => {
        wx.uploadFile({
          url: `${app.globalData.apiBaseUrl}/api/upload`,
          filePath,
          name: 'file',
          formData: {
            type: 'review'
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 200) {
                uploadedImages.push(data.data.url)
              } else {
                wx.showToast({
                  title: '图片上传失败',
                  icon: 'none'
                })
              }
            } catch (err) {
              console.error(err)
            }
          },
          fail: () => {
            wx.showToast({
              title: '图片上传失败',
              icon: 'none'
            })
          },
          complete: () => {
            uploadedCount++
            
            // 更新上传进度
            this.setData({
              uploadProgress: Math.floor((uploadedCount / images.length) * 100)
            })
            
            if (uploadedCount === images.length) {
              resolve(uploadedImages)
            }
          }
        })
      })
    })
  },

  // 提交评价
  async submitReview() {
    const { rating, content, userId, orderId, productId, storeId, anonymous, selectedTags } = this.data
    
    if (!rating) {
      wx.showToast({
        title: '请选择评分',
        icon: 'none'
      })
      return
    }
    
    if (!content.trim()) {
      wx.showToast({
        title: '请填写评价内容',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      submitting: true,
      uploadProgress: 0
    })
    
    wx.showLoading({
      title: '上传图片中',
      mask: true
    })
    
    try {
      // 先上传图片
      const uploadedImages = await this.uploadImages()
      
      wx.showLoading({
        title: '提交评价中',
        mask: true
      })
      
      // 提交评价
      wx.request({
        url: `${app.globalData.apiBaseUrl}/api/reviews`,
        method: 'POST',
        data: {
          userId,
          orderId,
          productId,
          storeId,
          rating,
          content: content.trim(),
          images: uploadedImages,
          anonymous,
          tags: selectedTags,
          type: 'PRODUCT'
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            wx.showToast({
              title: '评价成功',
              icon: 'success'
            })
            
            // 延迟返回
            setTimeout(() => {
              wx.navigateBack()
            }, 1500)
          } else {
            wx.showToast({
              title: res.data.message || '评价失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          })
        },
        complete: () => {
          wx.hideLoading()
          this.setData({
            submitting: false
          })
        }
      })
    } catch (err) {
      console.error(err)
      wx.hideLoading()
      wx.showToast({
        title: '评价失败',
        icon: 'none'
      })
      this.setData({
        submitting: false
      })
    }
  }
}) 